﻿using MvvmCross.Wpf.Views;
using Sidvall.UI.Views;
using Sidvall.WorkItemManager.UI.ViewModels;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace Sidvall.WorkItemManager.UI.Wpf.Views
{
	public partial class DashboardView : MvxWpfView, IView, IViewModelProvider
	{
		#region Public Members

		public new DashboardViewModel ViewModel
		{
			get
			{
				return (DashboardViewModel)base.ViewModel;
			}
			set
			{
				base.ViewModel = value;
			}
		}

		Sidvall.UI.ViewModels.IViewModel IViewModelProvider.ViewModel
		{
			get
			{
				return this.ViewModel;
			}
		}

		#endregion
		#region Constructors

		public DashboardView()
		{
			InitializeComponent();
		}

		#endregion

		#region Timer

		private DispatcherTimer Timer { get; set; }

		Task IView.OnViewEventAsync(ViewEventArgs args)
		{
			switch (args.EventType)
			{
				case ViewEventType.ViewCreated:
					if (this.Timer == null)
					{
						this.Timer = new System.Windows.Threading.DispatcherTimer();
						this.Timer.Tick += OnTimerTick;
						this.Timer.Interval = new System.TimeSpan(0, 0, 2);
						this.Timer.Start();
					}
					break;
				case ViewEventType.ViewUnloaded:
					if (this.Timer != null)
					{
						this.Timer.Stop();
						this.Timer = null;
					}
					break;
				default:
					break;
			}
			return Task.FromResult(true);
		}

		private async void OnTimerTick(object sender, System.EventArgs e)
		{
			if (this.ViewModel != null)
				await this.ViewModel.ReloadAsync();
		}

		#endregion
	}
}
